<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="一级表的ID" prop="calculatorId">
        <el-input
          v-model="queryParams.calculatorId"
          placeholder="请输入一级表的ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表A" prop="tableA">
        <el-input
          v-model="queryParams.tableA"
          placeholder="请输入表A"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段A" prop="fieldA">
        <el-input
          v-model="queryParams.fieldA"
          placeholder="请输入字段A"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表B" prop="tableB">
        <el-input
          v-model="queryParams.tableB"
          placeholder="请输入表B"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段B" prop="fieldB">
        <el-input
          v-model="queryParams.fieldB"
          placeholder="请输入字段B"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作符" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入操作符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conf:BiCalculatorOperations:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conf:BiCalculatorOperations:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conf:BiCalculatorOperations:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conf:BiCalculatorOperations:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="BiCalculatorOperationsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增主键" align="center" prop="id" />
      <el-table-column label="一级表的ID" align="center" prop="calculatorId" /> -->
      <el-table-column label="变量" align="center" prop="variable" />
      <el-table-column label="=" align="center">
        <template slot-scope="scope"> = </template>
      </el-table-column>

      <el-table-column label="字段A" align="center" prop="fieldA" />
      <el-table-column label="操作符" align="center" prop="operator" />
      <!-- <el-table-column label="表B" align="center" prop="tableB" /> -->
      <el-table-column label="字段B" align="center" prop="fieldB" />
      <el-table-column label="运算规则" align="center" prop="calcRules" />

      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conf:BiCalculatorOperations:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conf:BiCalculatorOperations:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用于存储与一级相关的操作符和字段信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="60%"
      append-to-body
      v-if="open"
    >
      <el-form ref="form" :model="form" label-width="80px" :inline="true">
        <el-form-item label="" prop="variable">
          <el-input
            v-model="form.variable"
            placeholder="请输入变量名"
            @blur="validateInput(form.variable)"
          />
        </el-form-item>
        <span
          style="
            margin-top: 20px;
            margin-right: 10px;
            font-size: 20px;
            font-weight: bold;
          "
          >=</span
        >
        <!-- <el-form-item label="表A" prop="tableA">
          <el-input v-model="form.tableA"343 placeholder="请输入表A" />
        </el-form-item> -->
        <el-form-item label="" prop="fieldA">
          <!-- <el-input v-model="form.fieldA" placeholder="请输入字段A" /> -->

          <el-select
            v-model="form.fieldAType"
            style="width: 120px"
            @change="changecompareValue(form.fieldAType, 'A')"
          >
            <el-option label="从表中选" value="table" />
            <el-option label="从变量中选" value="variable" />
            <el-option label="自定义" value="define" />
          </el-select>
          <el-input
            v-show="form.fieldAType == 'define'"
            style="width: 150px"
            v-model="form.fieldA"
            placeholder="请输入字段A"
          />
          <el-select
            v-show="form.fieldAType != 'define'"
            style="width: 150px"
            v-model="form.fieldA"
            placeholder="请输入字段A"
            clearable
            filterable
          >
            <el-option
              v-for="dict in tableNameList"
              :key="dict.field_name"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="operator">
          <!-- <el-input v-model="form.operator" placeholder="请输入操作符" />
           -->
          <el-select
            style="width: 100px"
            v-model="form.operator"
            placeholder="操作符"
          >
            <el-option label="+" value="+" />
            <!-- <el-option label="!=" value="NE" /> -->
            <el-option label="-" value="-" />
            <el-option label="*" value="*" />
            <el-option label="/" value="/" />
            <el-option label="自计算" value="calc" />
            <!-- <el-option label="<=" value="<=" />
            <el-option label="LIKE" value="LIKE" /> -->
            <!-- <el-option label="BETWEEN" value="BETWEEN" /> -->
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="表B" prop="tableB">
          <el-input v-model="form.tableB" placeholder="请输入表B" />
        </el-form-item> -->
        <!-- 日/周/月/季/年  day/week/month/season/year -->
        <el-form-item label="" prop="fieldB" v-show="form.operator == 'calc'">
          <el-select v-model="form.calcRules">
            <el-option label="日" value="day" />
            <el-option label="周" value="week" />
            <el-option label="月" value="month" />
            <el-option label="季" value="season" />
            <el-option label="年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="fieldB" v-show="form.operator != 'calc'">
          <el-select
            v-model="form.fieldBType"
            style="width: 120px"
            @change="changecompareValue(form.fieldBType, 'B')"
          >
            <el-option label="从表中选" value="table" />
            <el-option label="从变量中选" value="variable" />
            <el-option label="自定义" value="define" />
          </el-select>
          <el-input
            v-show="form.fieldBType == 'define'"
            style="width: 150px"
            v-model="form.fieldB"
            placeholder="请输入字段B"
          />
          <el-select
            v-show="form.fieldBType != 'define'"
            style="width: 150px"
            v-model="form.fieldB"
            placeholder="请输入字段B"
            clearable
            filterable
          >
            <el-option
              v-for="dict in tableNameList"
              :key="dict.field_name"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  variableList,
  listBiCalculatorOperations,
  getBiCalculatorOperations,
  delBiCalculatorOperations,
  addBiCalculatorOperations,
  updateBiCalculatorOperations,
} from "@/api/conf/BiCalculatorOperations";
import {
  listBiRuleSpecifications,
  getBiRuleSpecifications,
  delBiRuleSpecifications,
  addByRuleTage,
  updateBiRuleSpecifications,
  RuleTagger,
  getTablefieldsWithComments,
} from "@/api/conf/BiRuleSpecifications";
export default {
  name: "BiCalculatorOperations",
  props: {
    id: {
      type: Number,
      default: 0,
    },
    tableName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      variableList: [],
      compareValue: false,
      compareName: false,
      tableNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 用于存储与一级相关的操作符和字段信息表格数据
      BiCalculatorOperationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        calculatorId: null,
        tableA: null,
        fieldA: null,
        tableB: null,
        fieldB: null,
        operator: null,
        remarks: null,
      },
      // 表单参数
      form: {
        fieldAType: "table",
        fieldBType: "table",
      },
      // 表单校验
      rules: {
        calculatorId: [
          { required: true, message: "一级表的ID不能为空", trigger: "blur" },
        ],
        tableA: [{ required: true, message: "表A不能为空", trigger: "blur" }],
        fieldA: [{ required: true, message: "字段A不能为空", trigger: "blur" }],
        tableB: [{ required: true, message: "表B不能为空", trigger: "blur" }],
        fieldB: [{ required: true, message: "字段B不能为空", trigger: "blur" }],
        operator: [
          { required: true, message: "操作符不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // this.getList();
  },
  watch: {
    id: {
      handler: function (newnew, oldold) {
        console.log("newnew", newnew);
        if (newnew) {
          this.form.calculatorId = newnew;
          this.queryParams.calculatorId = newnew;
          // this.form.id=newnew
          this.getList();
          this.selectgetTablefieldsWithComments();
          // this.selectgetTablefieldsWithComments();
        }
        // this.showColumn = newnew;
        // // 这里需要让表格重新绘制一下，否则会产生固定列错位的情况
        // this.$nextTick(() => {
        //   this.$refs.BaseTable.doLayout();
        // });
      },
      deep: true,
      immediate: true,
    },
    tableName: {
      handler(newVal, oldVal) {
        console.log(newVal);
        if (!this.tableName) {
          return;
        }
        // this.tableName = this.queryParams.tableName;
        this.selectgetTablefieldsWithComments();
      },
    },
    // "form.fieldAType": {
    //   handler(newVal, oldVal) {
    //     if (this.form.fieldAType == "define") {
    //       this.form.fieldA = "";
    //     }
    //   },
    // },
    // "form.fieldBType": {
    //   handler(newVal, oldVal) {
    //     if (this.form.fieldBType == "define") {
    //       this.form.fieldB = "";
    //     }
    //   },
    // },
  },
  methods: {
    handlevariable() {},
    validateInput(value) {
      // 使用正则表达式检查输入是否为纯数字
      if (/^\d+$/.test(value)) {
        this.$modal.msgError("不允许纯数字");
        value = "";
      }
      if (this.variableList.includes(this.form.variable)) {
        this.$modal.msgError("已包含该变量");
      }
    },
    changecompareValue(compareValue, type) {
      if (compareValue == "table") {
        this.selectgetTablefieldsWithComments();
      } else if (compareValue == "variable") {
        variableList({ calculatorId: this.queryParams.calculatorId }).then(
          (response) => {
            let row = [];
            response.forEach((element) => {
              row.push({
                comment: element.variable,
                field_name: element.id,
              });
            });
            this.tableNameList = row;
          }
        );
      } else if (compareValue == "define") {
        if (type == "A") {
          this.form.fieldA = "";
        } else if (type == "B") {
          this.form.fieldB = "";
        }
      }
    },
    selectgetTablefieldsWithComments() {
      if (!this.tableName) {
        return;
      }
      getTablefieldsWithComments({ tableName: this.tableName }).then(
        (response) => {
          this.tableNameList = [];
          this.tableNameList = response;
        }
      );
    },
    /** 查询用于存储与一级相关的操作符和字段信息列表 */
    getList() {
      this.loading = true;
      listBiCalculatorOperations(this.queryParams).then((response) => {
        this.variableList = response.rows.map((item) => item.variable);
        console.log(JSON.stringify(this.variableList));

        this.BiCalculatorOperationsList = response.rows ? response.rows : [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // id: null,
        // calculatorId: null,
        variable: null,
        fieldAType: null,
        fieldBType: null,
        tableA: null,
        fieldA: null,
        tableB: null,
        fieldB: null,
        operator: null,
        remarks: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用于存储与一级相关的操作符和字段信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids;
      getBiCalculatorOperations(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用于存储与一级相关的操作符和字段信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiCalculatorOperations(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$emit("getFirstList");
            });
          } else {
            this.form.calculatorId = this.id;
            addBiCalculatorOperations(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$emit("getFirstList");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          '是否确认删除用于存储与一级相关的操作符和字段信息编号为"' +
            ids +
            '"的数据项？'
        )
        .then(function () {
          return delBiCalculatorOperations(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$emit("getFirstList");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "conf/BiCalculatorOperations/export",
        {
          ...this.queryParams,
        },
        `BiCalculatorOperations_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
